package com.ruoyi.web.controller.common;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.YoushudaUtils;
import com.ruoyi.system.youshuda.TableSupportInYsd;
import com.ruoyi.generator.domain.GenTableConfig;
import com.ruoyi.generator.service.IFromBuildConfigService;
import com.zgl.youshuda.core.domain.dto.ModelTablePageDomain;
import com.zgl.youshuda.core.logic.filedeal.FileDownloadVo;
import com.zgl.youshuda.core.service.procservice.InterDealProcService;
import com.zgl.youshuda.core.utils.CommonUtil;
import com.zgl.youshuda.core.utils.OperResult;
import com.zgl.youshuda.core.utils.poi.domain.ExcelColumn;
import com.zgl.youshuda.core.utils.poi.domain.ExcelConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 平台通过优树搭处理的公共基本增、删、改、查
 *
 * @author ZGL
 * @date 2024-09-30 14:12:25
 */
@RestController
@RequestMapping("/common/basemode")
public class BaseModeController extends BaseController {
    @Autowired
    private IFromBuildConfigService fromBuildConfigService;

    @Autowired
    private InterDealProcService ysdProcService;

    /**
     * 获取表字段信息，用于展示列表、查询区域字段显示
     *
     * @return
     */
    @GetMapping("/init/{menuTabId}")
    public AjaxResult getFieldInfo(@PathVariable String menuTabId) {
        if (StringUtils.isEmptyIncludeNull(menuTabId)) {
            return AjaxResult.error("模块表ID不能为空");
        }
        /**
         * 响应结果
         */
        return AjaxResult.success(fromBuildConfigService.getGenTableConfigIncludeColumn(menuTabId));
    }

    /**
     * 查询数据
     */
    @GetMapping("/list/{menuTabId}")
    public TableDataInfo list(@PathVariable String menuTabId, @RequestParam Map<String, Object> params) {
        try {
            /**
             * 调用优树搭流程API
             */
            OperResult exec = callYsdApi(menuTabId, params, TableSupportInYsd.List);
            //记录信息
            List rows = null;
            //总记录条数
            long total = 0;
            if (exec.isSuccess()) {
                Map data = JSONObject.parseObject(JSONObject.toJSONString(exec.getData()), Map.class);
                //记录信息
                rows = JSONObject.parseObject(JSONObject.toJSONString(data.get("result")), List.class);
                //总记录条数
                try {
                    total = Long.parseLong(String.valueOf(data.get("total")));
                } catch (Exception e) {
                    total = rows.size();
                }
            }
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(rows);
            rspData.setTotal(total);
            return rspData;
        } catch (Exception e) {
            logger.error("BaseModeController接口list异常", e);
            return null;
        }
    }

    /**
     * 获取详细信息
     */
    @GetMapping(value = "/{menuTabId}/{defPk}")
    public AjaxResult detail(@PathVariable("menuTabId") String menuTabId,
                             @PathVariable("defPk") String defPk,
                             @RequestParam(value = "clientType", defaultValue = "PC") String clientType) {
        try {
            /**
             * 参数对象解析
             */
            Map<String, Object> params = new HashMap<>();
            params.put("defPk", defPk);
            ModelTablePageDomain tablePageDomain = TableSupportInYsd.getPageParams(params);
            //根据业务表生成ID获取对应表配置信息
            GenTableConfig genTableConfig = fromBuildConfigService.getGenTableConfig(menuTabId);
            //表名
            tablePageDomain.setTableName(genTableConfig.getTableName());
            //Sql类型
            tablePageDomain.setSqlType(TableSupportInYsd.Detail);
            /**
             * 调用优树搭
             */
            OperResult exec = ysdProcService.dealProc(genTableConfig.getYsdDetailApi(), tablePageDomain);

            Map<String, Object> result = new HashMap<>();
            if (exec.isSuccess()) {
                //表单数据
                result.put("data", JSONObject.parseObject(JSONObject.toJSONString(exec.getData()), Map.class));
            }
            //表单设计字段配置信息
            result.put("formBuildConfig", fromBuildConfigService.getFormBuildConfig(genTableConfig.getFormBuildKey(), clientType));
            //返回结果
            return AjaxResult.success(exec.getMsg(), result);
        } catch (Exception e) {
            logger.error("BaseModeController接口detail异常", e);
            return AjaxResult.error("获取异常");
        }
    }

    /**
     * 新增数据
     */
    @PostMapping(value = "/{menuTabId}")
    public AjaxResult add(@PathVariable("menuTabId") String menuTabId,
                          @RequestBody Map<String, Object> params) {
        try {
            /**
             * 调用优树搭流程API
             */
            OperResult exec = callYsdApi(menuTabId, params, TableSupportInYsd.Add);
            if (exec.isSuccess()) {
                if (Integer.parseInt(String.valueOf(exec.getData())) > 0) {
                    return AjaxResult.success(exec.getMsg());
                }
            }
            return AjaxResult.error(exec.getMsg());
        } catch (Exception e) {
            logger.error("BaseModeController接口add异常", e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 修改数据
     */
    @PutMapping(value = "/{menuTabId}")
    public AjaxResult edit(@PathVariable("menuTabId") String menuTabId,
                           @RequestBody Map<String, Object> params) {
        try {
            /**
             * 调用优树搭流程API
             */
            OperResult exec = callYsdApi(menuTabId, params, TableSupportInYsd.Update);
            if (exec.isSuccess()) {
                if (Integer.parseInt(String.valueOf(exec.getData())) > 0) {
                    return AjaxResult.success(exec.getMsg());
                }
            }
            return AjaxResult.error(exec.getMsg());
        } catch (Exception e) {
            logger.error("BaseModeController接口edit异常", e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 删除数据
     */
    @DeleteMapping("/{menuTabId}/{defPks}")
    public AjaxResult remove(@PathVariable("menuTabId") String menuTabId,
                             @PathVariable String[] defPks) {
        try {
            if (defPks == null || defPks.length <= 0) {
                return AjaxResult.error("需要删除的数据ID不能为空");
            }
            String _defPks = Arrays.stream(defPks)
                    .collect(Collectors.joining(","));
            /**
             * 参数对象解析
             */
            Map<String, Object> params = new HashMap<>();
            params.put("defPk", _defPks);
            /**
             * 调用优树搭流程API
             */
            OperResult exec = callYsdApi(menuTabId, params, TableSupportInYsd.Delete);
            if (exec.isSuccess()) {
                if (Integer.parseInt(String.valueOf(exec.getData())) > 0) {
                    return AjaxResult.success(exec.getMsg());
                }
            }
            return AjaxResult.error(exec.getMsg());
        } catch (Exception e) {
            logger.error("BaseModeController接口remove异常", e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 导入数据
     */
    @PostMapping("/importData/{menuTabId}")
    public AjaxResult importData(@RequestParam("file") MultipartFile file,
                                 @PathVariable("menuTabId") String menuTabId,
                                 @RequestParam Map params) throws Exception {
        /**
         * 需要将平台的字段信息转换成优树搭指定的字段类型
         */
        GenTableConfig genTableConfig = fromBuildConfigService.getGenTableConfigIncludeColumn(menuTabId, false);
        //字段信息
        List<ExcelColumn> fields = JSONArray.parseArray(JSONObject.toJSONString(genTableConfig.getFieldInfos()), ExcelColumn.class);
        /**
         * 调用执行导入操作
         */
        OperResult operResult = ysdProcService.dealProc(file, genTableConfig.getYsdImportApi(), ExcelConfig.assParam(genTableConfig.getComponentDesc(), genTableConfig.getTableName(), fields, params));
        if (operResult.isSuccess()) {
            return AjaxResult.success(operResult.getMsg(), operResult.getData());
        }
        return AjaxResult.error(operResult.getMsg());
    }


    /**
     * 导入横版
     */
    @PostMapping("/importTemplate/{menuTabId}")
    public void importTemplate(HttpServletResponse response,
                               @PathVariable("menuTabId") String menuTabId) {
        export(response, menuTabId, null, TableSupportInYsd.ExportTemp);
    }

    /**
     * 导出列表数据
     */
    @PostMapping("/export/{menuTabId}")
    public void export(HttpServletResponse response,
                       @PathVariable String menuTabId,
                       @RequestParam Map<String, Object> params) {
        export(response, menuTabId, params, TableSupportInYsd.Export);
    }

    /**
     * 附件上传
     */
    @PostMapping("/upload")
    public AjaxResult fileUpload(MultipartFile file,
                                 @RequestParam("ysdApi") String ysdApi,
                                 @RequestParam("businessName") String businessName,
                                 @RequestParam("recordId") String recordId,
                                 @RequestParam("businessType") String businessType) throws Exception {
        if (StringUtils.isEmptyIncludeNull(ysdApi)) {
            return AjaxResult.error("优树搭处理文件的API编码不能为空");
        }
        /** 请求参数 **/
        Map<String, Object> reqData = new HashMap<>();
        //业务模块
        reqData.put("businessName", businessName);
        //业务数据ID
        reqData.put("recordId", recordId);
        //业务类型__自定义，当一个表单存在多个类型附件上传时
        reqData.put("businessType", businessType);
        /** 执行附件上传 **/
        OperResult exec = ysdProcService.dealProc(file, ysdApi, reqData);
        if (exec.isSuccess()) {
            Map data = JSONObject.parseObject(JSONObject.toJSONString(exec.getData()), Map.class);
            //资源映射路径 前缀
            data.put("ResourcePrefix", Constants.RESOURCE_PREFIX + "/");
            return AjaxResult.success(exec.getMsg(), data);
        }
        return AjaxResult.error(exec.getMsg(), exec.getData());
    }

    /**
     * 下载文件
     */
    @PostMapping("/download")
    public void fileDownload(HttpServletResponse response,
                             @RequestBody FileDownloadVo downloadVo) throws Exception {
        if (StringUtils.isEmptyIncludeNull(downloadVo.getYsdApi())) {
            throw new Exception(StringUtils.format("文件下载处理API编码不能为空！"));
        }
        if (StringUtils.isEmptyIncludeNull(downloadVo.getFilePath())) {
            throw new Exception(StringUtils.format("文件下载路径不能为空！"));
        }
        ysdProcService.dealProc(response, downloadVo.getYsdApi(), downloadVo);
    }


    /**
     * 调用优树搭流程API
     *
     * @param menuTabId
     * @param params
     * @param sqlType
     * @return
     */
    private OperResult callYsdApi(String menuTabId, Map<String, Object> params, String sqlType) {
        /**
         * 参数对象解析
         */
        ModelTablePageDomain tablePageDomain = TableSupportInYsd.getPageParams(params);
        //根据业务表生成ID获取对应表配置信息
        GenTableConfig genTableConfig = fromBuildConfigService.getGenTableConfig(menuTabId);
        //表名
        tablePageDomain.setTableName(genTableConfig.getTableName());
        //Sql类型
        tablePageDomain.setSqlType(sqlType);
        //Api编码
        String ysdAddApi = "";
        switch (sqlType) {
            case TableSupportInYsd.List:
                ysdAddApi = genTableConfig.getYsdListApi();
                //获取字段对应表单类型
                tablePageDomain.setParamsColumnInfo(fromBuildConfigService.getGenTableColumnConfig(genTableConfig.getTableId()));
                break;
            case TableSupportInYsd.Detail:
                ysdAddApi = genTableConfig.getYsdDetailApi();
                break;
            case TableSupportInYsd.Add:
                ysdAddApi = genTableConfig.getYsdAddApi();
                break;
            case TableSupportInYsd.Update:
                ysdAddApi = genTableConfig.getYsdUpdateApi();
                break;
            case TableSupportInYsd.Delete:
                ysdAddApi = genTableConfig.getYsdDeleteApi();
                break;
            default:
                return OperResult.errorInstance("调用优树搭时API编码匹配异常！");
        }
        /**
         * 调用优树搭
         */
        return ysdProcService.dealProc(ysdAddApi, tablePageDomain);
    }


    private void export(HttpServletResponse response, String menuTabId, Map<String, Object> params, String sqlType) {
        /**
         * 调用优树搭流程API
         */
        ModelTablePageDomain tablePageDomain = TableSupportInYsd.getPageParams(params);
        //根据业务表生成ID获取对应表配置信息
        GenTableConfig genTableConfig = fromBuildConfigService.getGenTableConfigIncludeColumn(menuTabId, false);
        //表名
        tablePageDomain.setTableName(genTableConfig.getTableName());
        //Sql类型
        tablePageDomain.setSqlType(sqlType);
        //字段信息
        if (genTableConfig.getFieldInfos() != null) {
            List<ExcelColumn> excelColumns = JSONArray.parseArray(CommonUtil.toJSONString(genTableConfig.getFieldInfos()), ExcelColumn.class);
            tablePageDomain.setFields(excelColumns);
        }
        //模块名称
        tablePageDomain.setModelName(genTableConfig.getComponentDesc());
        /**
         * 调用优树搭
         */
        ysdProcService.dealProc(response, genTableConfig.getYsdExportApi(), tablePageDomain);
    }

}
